const {ccclass, property} = cc._decorator;

@ccclass
export default class tankMove extends cc.Component {
    // LIFE-CYCLE CALLBACKS:

    // 坦克对象
    private tank:cc.Node

    @property(cc.Prefab)
    bullet: cc.Prefab = null;

    onLoad () {
        this.tank = this.node.getChildByName('tank');
        this.touchMove();
        
    }

    start () {
        this.attack();
    }
    // 坦克攻击
    attack() {
        // 获取当前场景
        let scene = cc.director.getScene()

        // 计时器，多少时间坦克攻击一次
        this.schedule(() => {
            // 创建子弹
            // 实例化预设体
            let newBullet = cc.instantiate(this.bullet);
            newBullet.setParent(this.node);
            // 设置子弹位置
            newBullet.x = this.tank.x;
            newBullet.y = this.tank.y + 40;
        }, 0.5);
        
        // 开启碰撞检测
        cc.director.getCollisionManager().enabled = true;
    }

    // 手指触摸控制坦克移动
    touchMove() {
        
        this.tank.on(cc.Node.EventType.TOUCH_MOVE, (e: cc.Touch)=> {
            let pos = this.node.convertToNodeSpaceAR(e.getLocation());
            let posX = pos.x;
            if(posX >= 210) {
                posX = 195;
            } else if (posX <= -210) {
                posX = -195;
            }
            this.tank.setPosition(posX, this.tank.y);
            // console.log(pos);
            
        }, this)
    }

    update (dt) {
    }
}
